# Copyright 2018 Tecnativa - Carlos Dauden
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
from odoo.addons import decimal_precision as dp
from odoo.tools.float_utils import float_compare, float_round
import logging


_logger = logging.getLogger(__name__)


class PurchaseOrderLine(models.Model):
    _inherit = 'purchase.order.line'

    secondary_uom_qty = fields.Float(
        string=u'数量(桶)',
        digits=dp.get_precision('Product Unit of Measure'),
    )
    secondary_uom_tx = fields.Float(
        string=u'规格(公斤/桶)',
        ondelete='restrict',
    )

    borrow = fields.Boolean(related='order_id.borrow')

    @api.onchange('secondary_uom_tx', 'secondary_uom_qty')
    def _onchange_secondary_uom(self):
        if not self.secondary_uom_tx:
            return
        factor = self.secondary_uom_tx
        qty = float_round(
            self.secondary_uom_qty * factor,
            precision_rounding=self.product_uom.rounding
        )
        if float_compare(
                self.product_qty, qty,
                precision_rounding=self.product_uom.rounding) != 0:
            self.product_qty = qty

    @api.onchange('product_qty')
    def _onchange_product_qty_purchase_order_secondary_unit(self):
        if not self.secondary_uom_tx:
            return
        factor = self.secondary_uom_tx
        qty = float_round(
            self.product_qty / (factor or 1.0),
            precision_rounding=self.product_uom.rounding
        )
        if float_compare(
                self.secondary_uom_qty, qty,
                precision_rounding=self.product_uom.rounding) != 0:
            self.secondary_uom_qty = qty

    @api.onchange('product_uom')
    def _onchange_product_uom_purchase_order_secondary_unit(self):
        if not self.secondary_uom_tx:
            return
        factor = self.secondary_uom_tx
        qty = float_round(
            self.product_qty / (factor or 1.0),
            precision_rounding=self.product_uom.rounding
        )
        if float_compare(
                self.secondary_uom_qty, qty,
                precision_rounding=self.product_uom.rounding) != 0:
            self.secondary_uom_qty = qty


class PurchaseOrder(models.Model):
    _inherit = 'purchase.order'

    borrow = fields.Boolean(string='借货')
